package sdk.webview.fmc.com.fmcsdk.presenter;


import android.text.TextUtils;
import android.view.View;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.base.BaseData;
import sdk.webview.fmc.com.fmcsdk.base.BasePresenter;
import sdk.webview.fmc.com.fmcsdk.base.UserApi;
import sdk.webview.fmc.com.fmcsdk.bean.IconBean;
import sdk.webview.fmc.com.fmcsdk.bean.ModfiyPassword;
import sdk.webview.fmc.com.fmcsdk.bean.SysSettingsInfoBean;
import sdk.webview.fmc.com.fmcsdk.bean.UploadImage;
import sdk.webview.fmc.com.fmcsdk.db.IMAGE;
import sdk.webview.fmc.com.fmcsdk.db.Record;
import sdk.webview.fmc.com.fmcsdk.interfaces.PresionInfoView;
import sdk.webview.fmc.com.fmcsdk.util.AESUtil;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.ImageUtils;
import sdk.webview.fmc.com.fmcsdk.util.SM2Utils;
import sdk.webview.fmc.com.fmcsdk.util.StringUtils;
import sdk.webview.fmc.com.fmcsdk.util.Url;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.XLog;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ApiFactory;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ResponseTransformer;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.ResponseSubscriber;

/**
 * Created by ydm on 2017/9/14.
 */

public class PresionInfoPresenter extends BasePresenter<PresionInfoView> {
    /**
     * 修改用户信息
     *
     * @param type    要修改的信息
     * @param content 修改内容
     */
    public void modifyUserInfo(final String type, final String content) {
        view.showLoading();
        getApi(UserApi.class).modifyUserInfo(getDefaultAddress() + Url.MODIFY_USER_INFO, Url.XMLHTTPREQUEST, UserHelper.getToken(), type, content)
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        view.ToastMessage(R.string.change_success);
                        view.modifyUserInfoSuccess(type, content);
                    }

                    @Override
                    public void onRequestAgain() {
                        modifyUserInfo(type, content);
                    }
                });
    }

    /**
     * 修改密码
     *
     * @param initialPassword 旧密码
     * @param newPassword     新密码
     * @param againPassword   确认新密码
     */
    public void modifyPassword(final String initialPassword, final String newPassword, final String againPassword) {
        view.showLoading();
        getApi(UserApi.class).modifyPassword(getDefaultAddress() + Url.MODIFY_PASSWORD, Url.XMLHTTPREQUEST, UserHelper.getToken(), initialPassword, newPassword)
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        view.ToastMessage(R.string.change_success);
                    }

                    @Override
                    public void onRequestAgain() {
                        modifyPassword(initialPassword, newPassword, againPassword);
                    }
                });
    }


    /**
     * 上传头像图片到客户端
     */
    public void uploadImgForClient() {
        XLog.i("uploadImgForClient");
        File files = new File(ImageUtils.getImagePath(Constant.TEMPSRCAVATAR, view.getViewContext()));
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), files);
        RequestBody timeBody = RequestBody.create(MediaType.parse("multipart/form-data"), System.currentTimeMillis()+"");//,+""

        getApi(UserApi.class).uploadImgForClient(getDefaultAddress() + Url.UPLOAD_IMG, Url.XMLHTTPREQUEST, UserHelper.getToken(), requestBody,null,timeBody)
                .compose(new ResponseTransformer<>(this.<UploadImage>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<UploadImage>(view) {
                    @Override
                    public void success(UploadImage baseData) {
                        XLog.i("uploadImgForClientsuccess");
                        //图片上传到服务器
                        uploadFilesServiceToIcon(baseData);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);

                        view.uploadImgForClientOnError();
                    }

                    @Override
                    public void onRequestAgain() {
                        uploadImgForClient();
                    }
                });

    }

    public void uploadImgForClient(final File file) {
        XLog.i("uploadImgForClient");
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        RequestBody timeBody = RequestBody.create(MediaType.parse("multipart/form-data"), System.currentTimeMillis()+"");//,+""

        getApi(UserApi.class).uploadImgForClient(getDefaultAddress() + Url.UPLOAD_IMG, Url.XMLHTTPREQUEST, UserHelper.getToken(), requestBody,null,timeBody)
                .compose(new ResponseTransformer<>(this.<UploadImage>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<UploadImage>(view) {
                    @Override
                    public void success(UploadImage baseData) {
                        XLog.i("uploadImgForClientsuccess");
                        //图片上传到服务器
                        uploadFilesServiceToIcon(baseData, file);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.uploadImgForClientOnError();
                    }

                    @Override
                    public void onRequestAgain() {
                        uploadImgForClient();
                    }
                });

    }

    /**
     * 头像上传到服务器
     */
    private void uploadFilesServiceToIcon(final UploadImage baseData) {
        getApi(UserApi.class).uploadImgForServer(getDefaultAddress() + Url.REPLACE_TOSTORE, Url.XMLHTTPREQUEST, UserHelper.getToken(), UserHelper.getToken(), UserHelper.getUserId(), "PA_STAFF", "ROLE_APP_ICON", baseData.getRecord().get(0).getId())
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        view.uploadImgForClientSuccess();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.uploadImgForClientOnError();
                    }

                    @Override
                    public void onRequestAgain() {
                        uploadFilesServiceToIcon(baseData);
                    }
                });
    }

    /**
     * 头像上传到服务器
     */
    private void uploadFilesServiceToIcon(final UploadImage baseData, final File file) {
        getApi(UserApi.class).uploadImgForServer(getDefaultAddress() + Url.REPLACE_TOSTORE, Url.XMLHTTPREQUEST, UserHelper.getToken(), UserHelper.getToken(), UserHelper.getUserId(), "PA_STAFF", "ROLE_APP_ICON", baseData.getRecord().get(0).getId())
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        view.uploadImgForClientSuccess(file);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.uploadImgForClientOnError();
                    }

                    @Override
                    public void onRequestAgain() {
                        uploadFilesServiceToIcon(baseData);
                    }
                });
    }


    /**
     * 上传数据库中的图片
     */
    public void uploadDBImg(final Record record, final int i) {
        File files = new File(ImageUtils.getH5ImagePath(record.getString("imageUrl"), view.getViewContext()));
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), files);
        RequestBody typeBody = RequestBody.create(MediaType.parse("multipart/form-data"), record.getString(IMAGE.TIMESTAMP));
        RequestBody timeBody = RequestBody.create(MediaType.parse("multipart/form-data"), System.currentTimeMillis()+"");//,+""

        getApi(UserApi.class).uploadImgForClient(getDefaultAddress() + Url.UPLOAD_IMG, Url.XMLHTTPREQUEST, UserHelper.getToken(), requestBody, typeBody,timeBody)
                .compose(new ResponseTransformer<>(this.<UploadImage>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<UploadImage>() {
                    @Override
                    public void success(UploadImage baseData) {
                        //图片上传到服务器
                        uploadFilesService(record, baseData.getRecord().get(0).getId(), i);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.uploadDBImgOnError();
                    }

                    @Override
                    public void onNext(UploadImage uploadImage) {
                        super.onNext(uploadImage);
                        //如果返回的是500也代表上传失败
                        if (uploadImage.getStatus().equals("500")) {
                            view.uploadDBImgOnError();
                        }
                    }

                    @Override
                    public void onRequestAgain() {
                        uploadDBImg(record, i);
                    }
                });
    }


    /**
     * 图片上传到服务器
     */
    private void uploadFilesService(final Record record, final String id, final int i) {
        getApi(UserApi.class).uploadImgForServer(getDefaultAddress() + Url.UPLOAD_FILES_SERVICE, Url.XMLHTTPREQUEST, UserHelper.getToken(), UserHelper.getToken(), record.getString("ownerId"), record.getString("ownerObject"), record.getString("ownerType"), id)
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        view.uploadDBImgsuccess(record, i);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.uploadDBImgOnError();
                    }

                    @Override
                    public void onRequestAgain() {
                        uploadFilesService(record, id, i);
                    }
                });
    }


    /**
     * 注销
     */
    public void logout() {
        view.showLoading();
        getApi(UserApi.class).logout(getDefaultAddress() + Url.LOGOUT, Url.XMLHTTPREQUEST, UserHelper.getToken())
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        view.ToastMessage(view.getViewContext().getString(R.string.logout_ok));
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {
                        logout();
                    }
                });
    }


    /**
     * 获取头像
     */
    public void getIconUrl() {
        getApi(UserApi.class).getIconUrl(getDefaultAddress() + Url.PROFILE_PHOTO + "?id=" + UserHelper.getUserId(), Url.XMLHTTPREQUEST, UserHelper.getToken())
                .compose(new ResponseTransformer<>(this.<IconBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<IconBean>(view) {
                    @Override
                    public void success(IconBean baseData) {
                        view.getIconUrlSuccess(baseData.getRecord());
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.getIconUrlError();
                    }

                    @Override
                    public void onRequestAgain() {
                        getIconUrl();
                    }
                });
    }

    public void getSM2Key(final String initialPassword, final String newPassword, String againPassword) {
        view.showLoading();
        getApi(UserApi.class).getSM2Key(getDefaultAddress() + Url.GET_SM2KEY, Url.XMLHTTPREQUEST)
                .compose(new ResponseTransformer<>(this.<ModfiyPassword>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<ModfiyPassword>() {
                    @Override
                    public void success(ModfiyPassword baseData) {
                        modifyPasswordChar(baseData.getRecord().getPublicKey(), initialPassword, newPassword);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {
                    }
                });
    }

    /**
     * 修改密码
     *
     * @param initialPassword 旧密码
     * @param newPassword     新密码
     */
    public void modifyPasswordChar(final String key, final String initialPassword, final String newPassword) {
        view.showLoading();
        getApi(UserApi.class).modifyPasswordChar(getDefaultAddress() + Url.MODIFY_PASSWORD, Url.XMLHTTPREQUEST, UserHelper.getToken(), key, SM2Utils.encode(key, initialPassword), SM2Utils.encode(key, newPassword))
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        view.ToastMessage(R.string.change_success);
                    }

                    @Override
                    public void onRequestAgain() {
                        modifyPasswordChar(key, SM2Utils.encode(key, initialPassword), SM2Utils.encode(key, newPassword));
                    }
                });
    }

    /**
     * 企业设置查询(现有接口)
     * "http://192.168.200.78"
     */
    public void sysSettingsInfo() {
        getApi(UserApi.class).sysSettingsInfo(getDefaultAddress() + Url.SYS_SETTING, Url.XMLHTTPREQUEST, System.currentTimeMillis() + "")
                .compose(new ResponseTransformer<>(this.<SysSettingsInfoBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<SysSettingsInfoBean>(view) {
                    @Override
                    public void success(SysSettingsInfoBean baseData) {
                        if (baseData.getRecords() == null) {
                            view.sysSettingsInfoFaiture();
                        } else {
                            UserHelper.saveSysSettingsInfoBean(baseData);
                            view.sysSettingsInfoSucess();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.sysSettingsInfoFaiture();
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {
                        view.sysSettingsInfoFaiture();
                    }

                });
    }


    /**
     * accessToken	Long	是	操作令牌
     * username	String	是	用户名
     * loginOldPwd	String	否	旧密码
     * loginNewPwd	String	否	新密码
     * encrypted	String	否	是否加密	3  固定写死
     * type 1 是忘记密码  0不是
     */
    public void editPwd(String username, String loginOldPwd, final String loginNewPwd, String type) {

        HashMap<String, String> map = new HashMap();
        map.put("username", username);
        map.put("loginOldPwd", AESUtil.encryptAESExpand(loginOldPwd)); //AES加密
        map.put("loginNewPwd", AESUtil.encryptAESExpand(loginNewPwd));
        map.put("defaultPwd", AESUtil.encryptAESExpand(UserHelper.getSysSettingsValueBycode("PWD_INIT")));  //初shi密码
        map.put("pwdComplexity", UserHelper.getSysSettingsValueBycode("PWD_COMPLEXITY"));  //复杂度
        map.put("pwdLen", UserHelper.getSysSettingsValueBycode("PWD_LEN"));  //密码长度
        map.put("type", type);
        map.put("encrypted", "3");
        Map<String, RequestBody> stringRequestBodyMap = StringUtils.generateRequestBody(map);
        ApiFactory.getFactory().create(UserApi.class).updatePwd(getDefaultAddress() + Url.UPDATE_PWD,
                "", stringRequestBodyMap)
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>() {
                    @Override
                    public void success(BaseData baseData) {
                        view.updatePwdSuccess(loginNewPwd);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {

                    }

                });
    }
}

